package org.dant.ant.extension.tasks;

import java.util.*;
import java.io.*;

import org.apache.tools.ant.BuildException;
import org.dant.ant.extension.tasks.commands.CopyCommand;
import org.dant.ant.extension.tasks.internal.RemoteResponse;

import org.apache.tools.ant.Project;

public class RCopy extends RemoteCopy {
  private int maxSize = 20*1024*1024;  // 20M bytes

  protected boolean complete = false;

  protected int blocks = 0;
  protected File file = null;

  protected int[] positions = null;
  protected int[] lengths = null;
  protected int totalSize = 0;

  protected int position = -1;
  protected int length = -1;

  protected int threshold = 20;
  protected String unit = "m";

  public void setThreshold(int threshold) {
    this.threshold = threshold;
  }

  public void setThresholdUnit(String unit) {
    this.unit = unit;
  }

  public int getPosition() {
    return this.position;
  }

  public int getLength() {
    return this.length;
  }

  public boolean getComplete() {
    return this.complete;
  }

  private void initThreshold() {
    if (threshold <= 0) this.threshold = 20;
    if (unit.length() < 1) this.unit = "m";
    
    char c = this.unit.charAt(0);
    switch (c) {
      case 'b':
      case 'B':
        maxSize = threshold;
        break;
      case 'k':
      case 'K':
        maxSize = threshold * 1024;
        break;
      case 'm':
      case 'M':
        maxSize = threshold * 1024 * 1024;
        break;
      case 'g':
      case 'G':
        maxSize = threshold * 1024 * 1024 * 1024;
        break;
    }
  }
  
  public void execute() throws BuildException {
    initThreshold();
    
    File src = new File(srcdir, filename);
    totalSize = (int) src.length();

    if (!src.exists())  throw new BuildException("File " + src.getAbsolutePath() + " is not exist");
    
    blocks = calcBlocks(totalSize);

    System.out.println("Total size: " + totalSize + " bytes, consist of " + blocks + " block(s)");

    if (blocks == 1) {
      this.complete = true;
      super.execute();
    } else {
      malloc();
      for (int i=0; i<blocks; i++) {
        this.position = positions[i];
        this.length = lengths[i];
        
      if (i == (blocks-1)) {
        this.complete = true;
      }
      super.execute();
      }
    }
    log("File " + src.getAbsolutePath() + " transfer completed!");
  }

  protected void handleResults(RemoteResponse response) {
  }

  private void malloc() {
    positions = new int[blocks];
    lengths = new int[blocks];
    
    for (int i=0; i<blocks; i++) {
      positions[i] = i*maxSize;
      lengths[i] = maxSize;
    }
    lengths[blocks-1] = maxSize - (maxSize*blocks - totalSize);
  }

  private int calcBlocks(int fileLen) {
    return (int) Math.ceil((double)fileLen/(double)maxSize);
  }
}
